package leetcode_周赛._2021._202104._20210404;

/**
 * @author yzh
 * @date 2021/4/4 10:32
 * 截断句子
 * 思路：
 *   按照空格来截
 *   如果要 5 个单词，那么需要 4 个空格
 */
public class _5722 {

    public String truncateSentence(String s, int k) {
        StringBuilder ans = new StringBuilder(), tem = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (k == 0) break;
            tem.append(s.charAt(i));
            if (s.charAt(i) == ' ' || i == s.length() - 1) {
                if (k == 1 && i != s.length() - 1) tem.delete(tem.length() - 1, tem.length());
                ans.append(tem.toString());
                tem.delete(0, tem.length());
                --k;
            }
        }
        return ans.toString();
    }
}
